/* ResourceManager.cpp
 * Manages the memory allocated to allegro objects, such as images and fonts
 *
 * Last Modified: 08.12.2013
 * Author: Guilherme S.G.
 *
 * TODO: what is the memory allocated by fonts and sounds roughly?
 */

#include "ResourceManager.h"

ResourceManager::ResourceManager()
{
    memoryAllocated = 0;
}

ResourceManager::~ResourceManager()
{
    for(int i = 0; i < images.size(); i++)
        al_destroy_bitmap(images[imageTags[i]]);
    images.clear();
    
    for(int i = 0; i < fonts.size(); i++)
        al_destroy_font(fonts[fontTags[i]]);
    fonts.clear();
    
    for(int i = 0; i < sounds.size(); i++)
        al_destroy_sample(sounds[soundTags[i]]);
    sounds.clear();
}

ALLEGRO_BITMAP* ResourceManager::loadImage(std::string filepath_, std::string tag_)
{
    ALLEGRO_BITMAP *image = nullptr;
    
    std::map<std::string,ALLEGRO_BITMAP*>::iterator it = images.find(tag_);
    
    if(it == images.end())
    {
        image = al_load_bitmap(filepath_.c_str());
        imageTags.push_back(tag_);
        images.insert(std::pair<std::string, ALLEGRO_BITMAP*>(tag_,image));
        
        //roughly 1byte (unsigned char) per pixel
        memoryAllocated += al_get_bitmap_width(image) * al_get_bitmap_height(image);
    }
    else
        image = it->second;
    
    return image;
}

ALLEGRO_FONT* ResourceManager::loadFont(std::string filepath_, int size_, int flags_, std::string tag_)
{
    ALLEGRO_FONT *font = nullptr;
    
    std::map<std::string,ALLEGRO_FONT*>::iterator it = fonts.find(tag_);
    
    if(it == fonts.end())
    {
        font = al_load_font(filepath_.c_str(), size_, flags_);
        fontTags.push_back(tag_);
        fonts.insert(std::pair<std::string, ALLEGRO_FONT*>(tag_,font));
        
        //memory allocated don't know
    }
    else
        font = it->second;
    
    return font;
}

ALLEGRO_SAMPLE* ResourceManager::loadSound(std::string filepath_, std::string tag_)
{
    ALLEGRO_SAMPLE *sound = nullptr;
    
    std::map<std::string,ALLEGRO_SAMPLE*>::iterator it = sounds.find(tag_);
    
    if(it == sounds.end())
    {
        sound = al_load_sample(filepath_.c_str());
        soundTags.push_back(tag_);
        sounds.insert(std::pair<std::string, ALLEGRO_SAMPLE*>(tag_,sound));
        
        //memory allocated don't know
    }
    else
        sound = it->second;
    
    return sound;
}


